<?php

namespace App\Helper;

use Curder\LaravelAliyunSms\AliyunSms;
use Illuminate\Support\Facades\Cache;

class SmsCode
{
    protected $aliyunSms;

    protected $templateCode = 'SMS_470405131';

    protected $cacheKey = 'sms_code';

    protected $ttl = 300;

    //发送间隔key
    protected $intervalKey = 'sms_interval';

    public function __construct(AliyunSms $aliyunSms)
    {
        $this->aliyunSms = $aliyunSms;
    }

    public function send($mobile)
    {
        //判断是否在60秒内发送过
        if (Cache::has($this->getIntervalKey($mobile))) {
            throw new \Exception('发送过于频繁，请稍后再试');
        }

        $code = $this->generateCode();
        $res = $this->aliyunSms->send($mobile, $this->templateCode, ['code' => $code]);

        if ($res->Code != 'OK') {
            throw new \Exception('短信发送失败'.$res->Message);
        }

        Cache::put($this->getSendKey($mobile), $code, $this->ttl);
        Cache::put($this->getIntervalKey($mobile), true, 60);

        return $res;
    }

    public function verify($mobile, $code)
    {
        $cacheCode = Cache::get($this->getSendKey($mobile));
        if ($cacheCode == $code)
            return true;

        return false;
    }

    public function verifyAndClean($mobile, $code)
    {
        if ($this->verify($mobile, $code)) {
            Cache::forget($this->getSendKey($mobile));
            return true;
        }
        return false;
    }

    protected function generateCode()
    {
        //生成 000000 - 999999 之间的随机数
        return str_pad(random_int(0, 999999), 6, 0, STR_PAD_LEFT);
    }

    protected function getSendKey($mobile)
    {
        return $this->cacheKey . $mobile;
    }

    protected function getIntervalKey($mobile)
    {
        return $this->intervalKey . $mobile;
    }
}
